package com.zhangmeng.online.exam.service.impl;

import com.zhangmeng.online.exam.dao.PermissionDao;
import com.zhangmeng.online.exam.dao.UserDao;
import com.zhangmeng.online.exam.entity.Permission;
import com.zhangmeng.online.exam.entity.Role;
import com.zhangmeng.online.exam.entity.User;
import com.zhangmeng.online.exam.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zm
 * @date 2025/3/22 15:43
 * @version: 1.0
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private UserDao userDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Permission> findByUserId(Long id) {
        Optional<User> userOptional = this.userDao.findById(id);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            List<Permission> permissions = new ArrayList<>();
            Set<Role> roles = user.getRoles();
            for (Role role : roles) {
                Set<Permission> permissions1 = role.getPermissions();
                permissions.addAll(permissions1);
            }
            return permissions;
        }
        return null;
    }


}
